package com.stoneframe.base.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.stoneframe.base.util.Logger;

//@Component("helloServer")
public class HelloServer {
	
	private static Logger logger=Logger.getLogger(HelloServer.class);
	
	private static final int portNumber=7878;
	
	@Autowired
	private HelloServerInitializer helloServerInitializer;
	
	public HelloServer(){
		
		logger.info("HelloServer###########################################");
		new Thread(new Runnable(){

			public void run() {
				// TODO Auto-generated method stub
				try {
					start();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}).start();
	}
	
	//程序初始方法入口注解，提示spring这个程序先执行这里
	//@PostConstruct
	public void start() throws InterruptedException{
		EventLoopGroup bossGroup=new NioEventLoopGroup();
		EventLoopGroup workGroup=new NioEventLoopGroup();
		try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(helloServerInitializer);
            // 服务器绑定端口监听
            ChannelFuture f = b.bind(portNumber).sync();
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();

            logger.info("###########################################");
            // 可以简写为
            /* b.bind(portNumber).sync().channel().closeFuture().sync(); */
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
	}

}
